﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; 
using System.IO;
using Wedo.Mvc.Utility;
using Wedo.Recognition.Domain.Models;
using Wedo.Recognition.Web.Controllers;
using Wedo.Recognition.Domain;
using Wedo.Mvc.Pager;
using Wedo.Domain.Models;
using Wedo.Mvc.Utility.Common;
using Wedo.Recognition.Service.BankImport;
using Wedo.Service.Common; 
using Wedo.Recognition.Repository;
using Wedo.Recognition.Service.Action;

namespace Wedo.IPRP.Web.Controllers
{
    public class PaymentApplyController : EntityController<PaymentApply, CommonSearchModel>
    {
        private PaymentService service;
        public PaymentApplyController(IUnitWork dbContext)
            : base(dbContext)
        {
            service = new PaymentService(_dbContext);
        }
 
 
        #region Finace 处理界面

        /// <summary>
        /// 所有认款
        /// </summary>
        /// <returns></returns>
        public override System.Web.Mvc.ActionResult Index()
        {
            //var where = new CommonSearchModel { Status = (int)ApprovalStatus.Waited };
            var where = new CommonSearchModel ();

            return Search(where);
        }


        public override ActionResult Edit(Guid id)
        {
            var model = FindById(id);
            if (model.CustomerName!=model.BankData.Payer.Trim() && model.BankData.PaymentApply.Count==1 )
                ViewData["CodeIsNotConfirm"] = true;

            UserService uService = new UserService(_dbContext);
            var list = uService.GetUserByRole("2").
                Select(m => new SelectListItem { Text = "是（" + m.StaffNameEN + " 审批）", Value = m.Name }).ToList();//财务
            list.Insert(0, new SelectListItem { Text = "否", Value = "" });

            list.ForEach(m => { if (m.Value == model.ReleaseOrder) { m.Selected = true; } });

            ViewBag.ReleaseOrder = list;//财务

            return ReturnAjaxView(model);
        }
         
        /// <summary>
        /// 待审批认款
        /// </summary>
        /// <returns></returns>
        public ActionResult WaitedPaymentAppy()
        {
            var where = new CommonSearchModel { Status = (int)ApprovalStatus.Waited };
            ViewData["SearchModel"] = where;
            var list=GetSearchPagedList(where);
            return ReturnAjaxView("Index", list);
        }

        /// <summary>
        /// 同意认款申请
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Agree(Guid id)
        {
            ResultMSG response = new ResultMSG();
             try
            {
                service.ApprovePayment(CurrentUserName, id);
                response.Result =true;
                response.MSG = Wedo.Recognition.Resources.ErrorMessage.RecognitionApplication;
            }
            catch (Exception ex)
            {
                response.Result =false;
                response.MSG = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 拒绝认款申请
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Reject(Guid id)
        {
            ResultMSG response = new ResultMSG();
             try
            {
                service.RejectPayment(CurrentUserName, id);
                response.Result =true;
                response.MSG = Wedo.Recognition.Resources.ErrorMessage.RefusedRecognizeApplications;
            }
            catch (Exception ex)
            {
                response.Result =false;
                response.MSG = ex.Message;
            }
            return Json(response);
        }

        [HttpPost]
        public string UploadFile(Guid id)
        {
            if (Request.Files.Count == 0 || Request.Files[0].FileName.IsNullOrWhiteSpace() )
            {
                return new ResultMSG("请选择一个文件").ToJson();
            }
            else
            {
                try
                {
                    var file = FileHelpers.SaveFile(Request.Files[0], Prefix: DateTime.Now.ToString("yyMMddHHmmss"));
                    string name = System.IO.Path.GetFileName(file);
                    PaymentAttach attach = new PaymentAttach();
                    attach.PaymentApplyId = id;
                    attach.ModifiedBy = CurrentUserName;
                    attach.CreatedBy = CurrentUserName;
                    attach.Status = 2;
                    attach.FileName =System.IO.Path.GetFileName(Request.Files[0].FileName);
                    attach.FilePath = Path.Combine("upload", name);
                    _dbContext.Set<PaymentAttach>().Create(attach);
                    return new ResultMSG(name, true).ToJson();
                }
                catch (Exception ex)
                {
                    return new ResultMSG(ex.Message).ToJson();
                }
            }
        }

        #endregion

        #region CSR处理界面

        public ActionResult MyPaymentApply()
        {
            ViewData["IsExport"]=true;
            var where = new CommonSearchModel {  ApplyMan = CurrentUserName };
            var list = GetSearchPagedList(where);
            
            ViewData["SearchModel"] = where;
            return ReturnAjaxView("Index", list);
        }

        public ActionResult ReportToDownload(CommonSearchModel where)
        {
            string name = DateTime.Now.ToString("yyyyMMddHHmmss") + "Bankdata.csv";
            var path = FileHelpers.GetRecivePath("TempDownload", name);
            var list = service.GetQuery(where).OrderBy(m => m.Created).ToList();
            UserService _uService = new UserService(_dbContext);
            var  expert = new PaymentApplyExpert(path,list);
            var users = _uService.GetAll().ToList();
            Dictionary<string, string> UserNames = new Dictionary<string, string>();
            foreach (var item in users)
            {
                UserNames[item.Name] = item.StaffNameEN;
            }
            expert.UserNames = UserNames;
            expert.Export();
            return File(path, "application/octet-stream", name);
        }

        /// <summary>
        /// 当前CSR等待审批的认款申请
        /// </summary>
        /// <returns></returns>
        public ActionResult MyWaitedPaymentApply()
        {
            var where = new CommonSearchModel { Status = (int)ApprovalStatus.Waited, ApplyMan = CurrentUserName };
            var list = GetSearchPagedList(where);
            ViewData["IsExport"] = true;

            ViewData["SearchModel"] = where;
            return ReturnAjaxView("Index", list);
        }

        /// <summary>
        /// 当前CSR已经审批通过的认款申请
        /// </summary>
        /// <returns></returns>
        public ActionResult MyApprovedPaymentApply()
        {
            var where = new CommonSearchModel { Status = (int)ApprovalStatus.Agree, ApplyMan = CurrentUserName };
            var list = GetSearchPagedList(where);
            ViewData["IsExport"] = true;

            ViewData["SearchModel"] = where;
            return ReturnAjaxView("Index", list);

        }

        /// <summary>
        /// 当前CSR被拒绝的认款申请
        /// </summary>
        /// <returns></returns>
        public ActionResult MyRejectedPaymentApply()
        {
            var where = new CommonSearchModel { Status = (int)ApprovalStatus.Reject, ApplyMan = CurrentUserName };
            var list = GetSearchPagedList(where);
            ViewData["IsExport"] = true;

            ViewData["SearchModel"] = where;
            return ReturnAjaxView("Index", list);

        }

        protected override PaymentApply FindById(Guid Id)
        {
            return service.GetAll(m => m.Id == Id,"BankData").FirstOrDefault();
        }

        /// <summary>
        /// 撤消认款申请
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Cancel (Guid id)
        {
            ResultMSG response = new ResultMSG();
            
            try
            {
                service.CancelPayment(CurrentUserName, id);
                response.Result =true;
                response.MSG = Wedo.Recognition.Resources.ErrorMessage.CancelRecognitionApplications;
            }
            catch (Exception ex)
            {
                response.Result =false;
                response.MSG = ex.Message;
            }
            return Json(response);
        }
        #endregion

        protected override Wedo.Service.Common.IBaseService<PaymentApply > EntityService
        {
            get { return service; }
        }

        protected override PagedList<PaymentApply> GetSearchPagedList(CommonSearchModel where)
        {
            //SetUserInfo();

            where = where ?? new CommonSearchModel(); 
            return service.GetQuery(where).OrderBy(m => m.Status)
                .ThenByDescending(m => m.Created).ToPagedList(where.Page, 10);
        }
    }
}
